/*
 * Copyright (C) 2010 http://laantiguafragua.blogspot.com/
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this library; if not, write to the Free
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * LoadXML.java
 *
 * Created on 02/24/2010
 */
package simplefileupdate;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.helpers.XMLReaderFactory;

/**
 * This class parse a XML in the SimpleFileUpdate format
 * @author lhrod
 */
public class LoadXML extends DefaultHandler {

    private XMLReader xr;
    private VersionData verData = new VersionData();
    ArrayList fileStack = new ArrayList();
    int top = 0;

    private LoadXML() {
    }

    /**
     * This class loads in a VersionData the content of a file appointed at the URL
     * @param uUpdate
     * @return VersionData with the XML information loaded
     * @throws IOException
     * @throws SAXException
     */
    public static VersionData loadURL(URL uUpdate) throws IOException, SAXException {
        URLConnection urlC = uUpdate.openConnection();
        return new LoadXML().parseXML(urlC.getInputStream());
    }

    private VersionData parseXML(InputStream iS) throws SAXException, IOException {
        xr = XMLReaderFactory.createXMLReader();
        xr.setContentHandler(this);
        xr.setErrorHandler(this);
        InputSource iSource = new InputSource(iS);
        xr.parse(iSource);

        return verData;
    }

    @Override
    public void startElement(String uri, String name, String qName, Attributes atts) {

        if ("file".equals(name.toLowerCase())) {
            int id = Integer.parseInt(atts.getValue("id"));
            fileStack.add(new Integer(id));
            String nameAtt = atts.getValue("name");
            SimpleDateFormat sDate = new SimpleDateFormat("mm/dd/yyyy");
            Date date = null;
            try {
                date = sDate.parse(atts.getValue("date"));
            } catch (ParseException ex) {
                Logger.getLogger(LoadXML.class.getName()).log(Level.SEVERE, null, ex);
            }
            URL url = null;
            String version = atts.getValue("version");
            try {
                url = new URL(atts.getValue("url"));
            } catch (MalformedURLException ex) {
                Logger.getLogger(LoadXML.class.getName()).log(Level.SEVERE, null, ex);
            }

            long size = -1;
            try {
                size = new Long(atts.getValue("size")).longValue();
            } catch (Exception ex) {
                Logger.getLogger(LoadXML.class.getName()).log(Level.SEVERE, null, ex);
            }

            boolean reloadApp = false;
            String value = atts.getValue("reloadapp");
            try {
                reloadApp = new Boolean(value).booleanValue();
            } catch (Exception ex) {
                reloadApp = false;
                if (value != null) {
                    Logger.getLogger(LoadXML.class.getName()).log(Level.SEVERE, null, ex);
                }
            }

            try {
                verData.addFile(id, nameAtt, date, url, version, size, reloadApp);
            } catch (Exception ex) {
                Logger.getLogger(LoadXML.class.getName()).log(Level.SEVERE, null, ex);
            }
        } else if ("news".equals(name.toLowerCase())) {
            top++;
        }
    }

    @Override
    public void characters(char[] text, int start, int length) {
        if (top > 0) {
            String txt = new String(text).substring(start, start + length);
            if (fileStack.size() <= 0) {
                verData.addNews(txt);
            } else {
                int last = fileStack.size() - 1;
                verData.addNews(txt, ((Integer) fileStack.get(last)).intValue());
            }
        }
    }

    @Override
    public void endElement(String uri, String name, String qName) {
        if ("news".equals(name.toLowerCase())) {
            top--;
        } else if ("file".equals(name.toLowerCase())) {
            fileStack.remove(fileStack.size() - 1);
        }
    }
}
